package top.aiprogram.common.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.xml.transform.Result;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtils {

    private static String driver = "com.mysql.cj.jdbc.Driver";
    private static String url = "jdbc:mysql://192.168.100.240:3306/studentmanage";
    private static String user = "root";
    private static String password = "123456";

    public static Connection getConn()throws Exception{//链接数据库
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setJdbcUrl(url);
        dataSource.setDriverClass(driver);
        dataSource.setUser(user);
        dataSource.setPassword(password);

        Connection conn =  dataSource.getConnection();
        return conn;
    }

    //释放数据库资源
    //ResultSet 用于执行静态SQL语句并返回它所生成的结果对象
    //PreparedStatement 对于可执行的sql语句执行预编译，存入到缓存中，下次编译时相同的sql语句不会被编译，提高
    //执行效率，相对于Statment 可维护性可读性更高
    //preparedStatement.executeUptate为更新sql
    public static void close(ResultSet resultSet , PreparedStatement preparedStatement, Connection conn){
        try {
            if(resultSet!=null){
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if(preparedStatement!=null){
                preparedStatement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if(conn!=null){
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
